﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using WebApp.BaseDataSvc;
using System.IO;

namespace WebApp
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class DownloadHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            try
            {
                if (!string.IsNullOrEmpty(context.Request.Params["Id"]))
                {
                    BaseDataSvc.BaseDataClient bdProxy = new BaseDataClient();
                    bdProxy.Open();
                    TB_Attach attach = bdProxy.GetAttach(Convert.ToInt32(context.Request.Params["Id"]));
                    bdProxy.Close();
                    string fullPath = Path.Combine(WebCommon.GetUploadFileDir(attach.createTime), attach.createTime.ToString("yyyyMMddHHmmss") + "_" + attach.@operator.ToString() + attach.ext);
                    if (!File.Exists(fullPath))
                        fullPath = Path.Combine(WebCommon.GetUploadFileDir(attach.createTime), attach.attachName);
                    downloadfile(fullPath);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        void downloadfile(string filePath)
        {
            if (File.Exists(filePath))
            {
                HttpContext.Current.Response.ContentType = "application/ms-download";
                System.IO.FileInfo file = new System.IO.FileInfo(filePath);
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
                HttpContext.Current.Response.Charset = "utf-8";
                HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8));
                HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
                HttpContext.Current.Response.WriteFile(file.FullName);
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.Clear();
            }
            else
                HttpContext.Current.Response.Write("文件不存在！");
            HttpContext.Current.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
